<template>
	<view class="driverClass">
		<uni-nav-bar
			color="#ffffff"
			background-color="#00aded"
			:status-bar="true"
			title="司机管理"
			fixed="true"
			left-icon="left"
			left-text="返回"
			@clickLeft="back"
			right-icon="personadd-filled"
			@clickRight="addDriver"
		/>
		<view class="driverTop">
			<dil-search :columnData="options.columnDataList" @onSearch="onSearch" v-if="options.columnDataList.length > 0"></dil-search>
		</view>
		<view class="driverMain">
			<uni-section :title="title" sub-title="" type="line">
				<dil-card class="dilCard" @emitEvent="emitEvent" v-bind.sync="options"></dil-card>
			</uni-section>
		</view>
		<view class="driverPop">
			<uni-popup ref="popup" type="dialog">
				<view class="popContent">
					<view class="main">
						<dil-Form ref="form" :formId="470" v-model="form" labelPosition="left" labelWidth="90px" v-if="formShow"></dil-Form>
					</view>
					<view class="footer">
						<button type="default" @click="canceAdd">取消</button>
						<button type="primary" @click="confirmAdd">确认</button>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script>
import { mapState } from 'vuex';
import nfc from '@/utils/nfc.js';
import { previewImageList } from '@/utils/utils.js';
export default {
	data() {
		return {
			form: {},
			formShow: false,
			driverList: [],
			uniList: [],
			fileDisposeMap: [
				{
					name: 'personnelName',
					label: '驾驶证',
					prop: 'driverLisencePhoto'
				}
			],
			imageList: [],
			mode: 'round',
			needUpdateList: [
				{ before: 'personnelName', after: 'PERSONNEL_NAME' },
				{ before: 'identityCard', after: 'IDENTITY_CARD' },
				{ before: 'drivingPermitNo', after: 'DRIVING_PERMIT_NO' },
				{ before: 'businessPermitNo', after: 'BUSINESS_PERMIT_NO' }
			],
			options: {
				requestUrl: '/api/v1/rms/getPersonnelList?apiId=341',
				requestQuery: {},
				cardSlotList: [
					{
						label: '激活身份证',
						icon: 'scan',
						emitEvent: 'enableIdCard',
						showCondition: 'item.innerCode == null',
						noPre: '1'
					},
					{
						label: '重新激活身份证',
						icon: 'scan',
						emitEvent: 'enableIdCard',
						showCondition: 'item.innerCode != null',
						noPre: '1'
					},
					{
						label: '修改',
						icon: 'wlIcon-shouquan',
						emitEvent: 'updateInfo',
						noPre: '1'
					}
				],
				columnDataList: [],
				totalNum: 0
			}
		};
	},
	onShow() {
		uni.$emit('onShow', 1);
	},
	created() {
		this.initialMap = {};
		this.initialMap.personnelPost = '司机';
		this.initialMap.personnelTeam = uni.getStorageSync('personnelTeam');
		let selfPost = uni.getStorageSync('personnelPost');
		if (selfPost != null && selfPost == '司机') {
			this.initialMap.personnelId = uni.getStorageSync('personnelId');
		}
		this.options.requestQuery = this.initialMap;
	},
	computed: {
		title() {
			return `共${this.options.totalNum}位司机`;
		},
		...mapState('common', ['innerCode'])
	},
	watch: {
		innerCode(val) {
			console.log(val, 'val');
		},
		'form.personnelJobNumber'(val) {
			if (val && val.length > 1) {
				this.getDriverInfoDebounce(val);
			}
		},
		'form.identityCard'(val) {
			this.form.drivingPermitNo = val;
		}
	},
	mounted() {
		this.getDriverInfoDebounce = this.Tool.debounce((val) => {
			this.getDriverInfo(val);
		}, 1500);
	},
	methods: {
		async getDriverInfo(val) {
			const res = await this.$myRequest({
				url: '/api/v1/uc/getDriverInfo',
				data: {
					jobNumber: val
				}
			});
			if (res.data.status == 'succeed' && res.data.data) {
				this.needUpdateList.forEach((item) => {
					this.$set(this.form, item.before, res.data.data[item.after]);
				});
				if (res.data.data.DRIVER_LISENCE_PHOTO) {
					previewImageList(res.data.data.DRIVER_LISENCE_PHOTO).then((r) => {
						this.$set(this.form, 'driverLisencePhoto', r);
					});
				}
			}
		},
		closeNfc() {
			nfc.closeNFC();
		},
		listenNfc() {
			nfc.initNFC();
		},
		runNfc(callback) {
			nfc.readNFC(callback);
		},
		//获取司机信息
		async getDriverList() {
			this.options.requestQuery = { ...this.options.requestQuery };
		},
		onSearch(item) {
			this.options.requestQuery = { ...JSON.parse(JSON.stringify(item)), ...this.initialMap };
		},
		searchInput(value) {
			this.uniList = this.driverList.filter((e) => {
				return `${e.personnelPhone}${e.personnelName}`.includes(value);
			});
		},
		back() {
			uni.switchTab({
				url: '/pages/myInfo/myInfo'
			});
		},
		addDriver() {
			this.$refs.popup.open();
			this.formShow = true;
		},
		confirmAdd() {
			this.$refs['form'].validateForm((data) => {
				if (data.flag) {
					this.Tool.uploadFile(this.form, ['driverLisencePhoto'], (response) => {
						this.addDriverInfo(response);
					});
				} else {
					console.log('res: ');
				}
			});
		},
		canceAdd() {
			this.formShow = false;
			this.form = {};
			this.getDriverList();
			this.$refs.popup.close();
		},
		async addDriverInfo(data) {
			data.roleId = '';
			data.ssoId = '';
			data.roleIds = [];
			data.personnelPhone = data.personnelJobNumber;
			data.personnelPost = '司机';
			let url = '/api/v1/rms/insertPersonnel';
			if (data.updateFlag == 'update') {
				url = '/api/v1/rms/updatePersonnel';
			}
			const res = await this.$myRequest({
				url: url,
				data: data
			}).catch((err) => {
				uni.showToast({
					duration: 2000,
					title: err,
					icon: 'error'
				});
			});
			if (res.data.status == 'succeed') {
				uni.showToast({
					icon: 'success',
					title: '新增成功',
					duration: 2000
				});
				this.canceAdd();
				this.form = {};
			} else {
				uni.showToast({
					icon: 'none',
					title: res.data.message,
					duration: 2000
				});
			}
		},
		emitEvent(eventName, cardItem) {
			this[eventName](cardItem);
		},
		updateInfo(item) {
			console.log(item, 'item');
			this.form = item;
			this.$refs.popup.open();
			this.form.updateFlag = 'update';
			this.formShow = true;
		},
		async enableIdCard(item) {
			// #ifdef APP-PLUS
			console.log(uni.getSystemInfoSync().platform, 'app');
			if (uni.getSystemInfoSync().platform == 'android') {
				uni.showToast({
					duration: 3000,
					title: '请根据提示操作',
					icon: 'none'
				});
				await this.listenNfc();
				await this.runNfc(async (data) => {
					console.log(data, 'data');
					if (data.includes('00000000000')) {
						uni.showToast({
							duration: 2000,
							title: '识别失败,请重新识别',
							icon: 'none'
						});
						return;
					}
					let map = {
						driverId: item.personnelId,
						innerCode: data
					};
					const res = await this.$myRequest({
						url: '/api/v1/rms/updateInnerCode',
						data: map
					}).catch((err) => {
						uni.showToast({
							duration: 2000,
							title: err,
							icon: 'error'
						});
					});
					if (res.data.status == 'succeed') {
						uni.showToast({
							icon: 'success',
							title: '更新成功',
							duration: 2000
						});
					} else {
						uni.showToast({
							icon: 'error',
							title: '更新失败',
							duration: 2000
						});
					}
					this.getDriverList();
				});
			} else {
				uni.showToast({
					duration: 2000,
					title: '请使用安卓手机下载应用激活',
					icon: 'none'
				});
			}
			// #endif
			// #ifdef H5
			uni.showToast({
				duration: 2000,
				title: '浏览器端不支持激活身份证,请使用安卓手机下载应用激活',
				icon: 'none'
			});
			// #endif
		}
	}
};
</script>

<style lang="scss" scoped>
.driverClass {
	display: flex;
	flex-direction: column;
	width: 100%;
	height: 100%;
	background-color: #f5f5f5;
	.driverTop {
		margin-top: 20rpx;
		background-color: #fff;
	}
	.driverMain {
		margin-top: 20rpx;
		background-color: #fff;
	}
	.driverPop {
		.popContent {
			width: 90vw;
			height: 100%;
			background-color: #fff;
			.main {
				padding-top: 60rpx;
				margin-left: 20rpx;
			}
			.footer {
				display: flex;
				margin-top: 80rpx;
				margin-bottom: 40rpx;
				u-button {
					// width: 80px
				}
			}
		}
	}
	.popContent {
		width: 100vw;
		height: 100%;
		background-color: #fff;
		.main {
			padding-top: 50rpx;
			margin-left: 15rpx;
			// display: flex;
			// justify-content: center;
			// align-items: center;
			// flex-direction: column;
			.downloadFile {
				margin-bottom: 20rpx;
			}
			.swiper-box {
				height: 50vh;
				margin-left: 20rpx;
			}
			.footer {
				display: flex;
				margin-top: 20rpx;
				// margin-bottom: 20rpx;
				u-button {
					// width: 80px
				}
			}
		}
	}
}
</style>
